#'
#'  Project title:     'Sovereign Risk and Government Change: Elections, Ideology and Experience'
#'  Authors:           Sarah M. Brooks; Raphael Cunha; Layna Mosley
#'  File description:  Event study; calculates median abnormal changes in sovereign spreads
#                      in elections
#'  Output:            Tables 1-2; Tables A1-A2; Figures A1-A4
#'

# my_packages <- c("tidyverse", "ggrepel",
#                  "countrycode", "rio")
# install.packages(my_packages)

library(ggrepel)
library(tidyverse)
library(countrycode)
library(rio)

# Set directories

DATADIR <- "~/.../Data/Daily"

# Load EMBI and CDS datasets

load(file = file.path(DATADIR, "EMBI Spreads and Elections.Rdata"))
load(file = file.path(DATADIR, "CDS Spreads and Elections.Rdata"))


# Estimate typical abnormal spread change in non-electoral periods --------

# Compute empirical distribution of median abnormal
# changes in spreads in non-political periods

# Distinguish political periods (campaign, election) from non-political ones
# Exclude political periods from computation

politicalPeriods <- function(data, election_id_var) {
  
  data$elec_id <- data[, election_id_var]
  data$elec_id <- as.character(data$elec_id)
  ids <- unique(data$elec_id[!is.na(data$elec_id)])
  
  for (i in ids){
    
    # Political period (within 6 months/180 days of an election)
    # (add another 90 days to ensure sampled periods have miminum number of obs for estimation)
    
    political_period_dates <- seq.Date(unique(max(data[which(data$elec_id == i), ]$date)) - (180 + 90), 
                                       unique(max(data[which(data$elec_id == i),]$date)) + 180,
                                       by = 1)
    
    country <- as.character(unique(data[which(data$elec_id == i),]$country))
    data$political_period[data$country == country & data$date %in% political_period_dates] <- 1
  }
  
  data$political_period[is.na(data$political_period)] <- 0
  
  countries <- unique(data$country)
  
  # Block 90 days at end of time series to ensure
  # minimum length of sequence for estimation
  
  for(j in countries){
    
    end_of_series_dates <- seq.Date((max(data$date[which(data$country == j)]) - 90), 
                                    max(data$date[which(data$country == j)]),
                                    by = 1)
    
    data$end_series[data$country == j & data$date %in% end_of_series_dates] <- 1
  }
  
  data$end_series[is.na(data$end_series)] <- 0
  
  # Indicator of obs to be excluded from calculation
  # of empirical distribution
  
  data$exclude <- ifelse(data$political_period == 1 | data$end_series == 1, 1, 0)
  
  return(data)
}

embig <- politicalPeriods(data = embig,
                          election_id_var = "election1r_id")

cds <- politicalPeriods(data = cds,
                        election_id_var = "election1r_id")

# Boostrap empirical distribution of median abnormal
# returns in non-political periods

bootCI <- function(n_boot, dep_var, market_vars, conf_level, data){
  
  # List with output
  
  CI_out <- list()
  countries <- unique(data$country)
  
  for(i in countries){
    
    sub_dat <- subset(data, country == i)
    
    # Take random samples of non-political periods
    
    B <- n_boot
    boot_out <- matrix(NA, nrow = B, ncol = 2)
    
    set.seed(12345)
    full_samp_date <- sample(sub_dat$date[sub_dat$exclude == 0], B, replace = TRUE)
    
    for(j in 1:length(full_samp_date)){
      
      samp_date <- full_samp_date[j]
      
      # Get 1 year of weekly returns for model estimation
      
      samp_seq <- seq.Date(from = samp_date,
                           to = samp_date + 126,
                           by = 1)
      
      boot_dat <- sub_dat[which(sub_dat$date %in% samp_seq), ]
      
      if(nrow(boot_dat) < 40) next
      
      # Estimate market model
      
      fmla <- paste(dep_var, " ~ ", paste(market_vars, collapse = "+"), sep = "")
      mm <- lm(fmla, data = boot_dat)
      
      # Get excess/abnormal returns
      
      AR <- resid(mm)
      nobs <- nobs(mm)
      
      # Get median AR in the period
      
      boot_out[j,c(1,2)] <- c(median(AR),
                              nobs)
    }
    
    # Get mean, median, and 95% CI from bootstrapped distribution
    
    ci <- quantile(boot_out[,1],
                   probs = c(0.5, ((1 - conf_level)/2), (1 - (1 - conf_level)/2)),
                   na.rm = TRUE)
    mean_AR <- mean(boot_out[,1], na.rm = TRUE)
    nobs_min <- min(boot_out[,2], na.rm = TRUE)
    nobs_max <- max(boot_out[,2], na.rm = TRUE)
    n_boot <- length(boot_out[,1][!is.na(boot_out[,1])])
    
    df <- data.frame(country = i,
                     avg_median_AR = mean_AR,
                     median_median_AR = ci[1],
                     lb = ci[2],
                     ub = ci[3],
                     min = nobs_min,
                     max = nobs_max,
                     n_boot = n_boot,
                     stringsAsFactors = FALSE)
    
    CI_out[[length(CI_out) + 1]] <- df
  }
  
  CI_out <- do.call("rbind", CI_out)
  return(CI_out)
}

CI_embig <- bootCI(n_boot = 5000,
                   dep_var = "d_embispread",
                   market_vars = c("d_spread_index", "d_treasury10y", "d_oil", "d_vix"),
                   conf_level = 0.90,
                   data = embig)

CI_cds <- bootCI(n_boot = 5000,
                 dep_var = "d_cdsspread",
                 market_vars = c("d_spread_index", "d_treasury10y", "d_oil", "d_vix"),
                 conf_level = 0.90,
                 data = cds)


# Estimate abnormal spread changes during elections -----------------------

# Compute median abnormal changes in spreads
# during campaign periods
# Obs.: disable txtProgessBar for Mexico case (single case)

medianAR <- function(window, election_id_var, dep_var, L1_length, market_vars, data){
  
  # Definitions:
  # window = vector w/ number of weeks pre- and post-election to include in event window
  # L1 = estimation window length in weeks
  # market_vars = regressors for the market model
  
  # Set event window limits
  w1 <- window[1]
  w2 <- window[2]
  
  # Estimation window length
  L1 <- L1_length
  
  # Set election ID variable
  data$elec_id <- data[, election_id_var]
  data$elec_id <- as.character(data$elec_id)
  
  # Country IDs for looping
  countries <- unique(data$country)
  
  # Lists to store results
  AR_out <- list() # Main list of median ARs

  for (k in countries){
    
    cntry_dat <- subset(data, country == k)
    ids <- na.omit(unique(cntry_dat$elec_id))
    
    for (i in ids){
      
      # Define event window
      event_window <- seq.Date(unique(max(cntry_dat[which(cntry_dat$elec_id == i), ]$date)) - w1,
                               unique(max(cntry_dat[which(cntry_dat$elec_id == i),]$date)) + w2,
                               by = 1)
      
      estimation_window <- seq.Date(unique(cntry_dat[which(cntry_dat$elec_id == i), ]$date) - (185 + L1), # L1 = est. window length in days
                                    unique(cntry_dat[which(cntry_dat$elec_id == i),]$date) - (185),
                                    by = 1)
      
      # Subset data
      AR_dat <- cntry_dat[which(cntry_dat$date %in% event_window |
                                  cntry_dat$date %in% estimation_window), ]
      
      # Add event and estimation window indicators
      AR_dat$event_window <- ifelse(AR_dat$date %in% event_window, 1, 0)
      AR_dat$estimation_window <- ifelse(AR_dat$date %in% estimation_window, 1, 0)
      
      # Skip case if estimation window < 40 weeks/observations
      
      if(nrow(AR_dat[AR_dat$estimation_window == 1, ]) < 60) next

      # Obtain country-specific returns (ARs) from market model
      
      # Estimate market model
      
      fmla <- paste(dep_var, " ~ ", paste(market_vars, collapse = "+"), sep = "")
      mm <- lm(fmla, data = AR_dat[AR_dat$estimation_window == 1, ])
      
      # Get excess/abnormal returns
      
      pred <- predict(mm, newdata = AR_dat[AR_dat$event_window == 1, ]) # Out-of-sample predictions for event window
      AR <- AR_dat[,dep_var][AR_dat$event_window == 1] - pred # Abnormal returns for event window
      nobs <- nobs(mm)
      
      df <- data.frame(country = as.character(k),
                       election = i,
                       year = as.numeric(unique(AR_dat$year[which(AR_dat$elec_id == i)])),
                       date = unique(AR_dat$date[which(AR_dat$elec_id == i)]),
                       AR = median(AR, na.rm = TRUE),
                       L2 = nobs,
                       stringsAsFactors = FALSE)
      
      AR_out[[length(AR_out) + 1]] <- df

    }
  }
  
  AR_out <- do.call("rbind", AR_out)
  return(AR_out)
}

# Estimate median ARs in election periods

median_AR_embig <- medianAR(window = c(90,0),
                            election_id_var = "election1r_id",
                            dep_var = "d_embispread",
                            market_vars = c("d_spread_index", "d_treasury10y", "d_oil", "d_vix"),
                            L1_length = 180,
                            data = embig)

median_AR_cds <- medianAR(window = c(90,0),
                          election_id_var = "election1r_id",
                          dep_var = "d_cdsspread",
                          market_vars = c("d_spread_index", "d_treasury10y", "d_oil", "d_vix"),
                          L1_length = 180,
                          data = cds[cds$em == 1, ])



# Plots and tables for EMBI spread event study ----------------------------

# Merge in empirical EMBI CIs 

median_AR_dat <- left_join(median_AR_embig, CI_embig, by = "country")
plot_var <- "EMBI"   # Set dep. var name for plot labels/file names
plot_window <- "90"  # Set # of days of event window for plot labels

# Country codes
median_AR_dat$iso3c <- countrycode(median_AR_dat$country, origin = "country.name", destination = "iso3c")

# Election labels
median_AR_dat$label <- paste(median_AR_dat$iso3c, format(median_AR_dat$date, "%Y/%m"), sep = " ")

# Indicator of statistical significance
median_AR_dat$sig <- ifelse(median_AR_dat$AR < median_AR_dat$lb | median_AR_dat$AR > median_AR_dat$ub, 1, 0)

# Number of cases with unusual median ARs
sum(median_AR_dat$sig)
sum(median_AR_dat$sig)/nrow(median_AR_dat)

# Break down by median ARs that are lower or higher than average
sum(median_AR_dat$sig[median_AR_dat$AR < median_AR_dat$lb])/nrow(median_AR_dat)
sum(median_AR_dat$sig[median_AR_dat$AR > median_AR_dat$ub])/nrow(median_AR_dat)

# Excess spread change during election
median_AR_dat$excess_AR <- median_AR_dat$AR/median_AR_dat$median_median_AR


# Plot event study results

# Convert to long format
plot_dat <- subset(median_AR_dat,
                   select = c(country, iso3c, date, year, AR, excess_AR, lb, ub, sig, label))

plot_dat$sig_charac <- ifelse(plot_dat$sig == 1, "Market Reaction", "No Market Reaction")

# Plot median AR by change in partisanship; executive turnover

# DPI: ideology and time in office

dpi <- import(file = file.path(DATADIR, "DPI2015.dta"), format = "dta")

dpi$iso3c <- countrycode(dpi$ifs, origin = "wb", destination = "iso3c", warn = TRUE)

dpi$execrlc[dpi$execrlc == -999] <- NA
dpi$execrlc[dpi$execrlc == 0] <- NA

# Recode variables

dpi_ideol <- dpi %>%
  group_by(iso3c) %>%
  mutate(d_rlc = c(NA, diff(execrlc)), # Change in ideology
         lead_d_rlc = dplyr::lead(d_rlc), # Lead change variable by 1 year
         lead_execrlc = dplyr::lead(execrlc), # Lead rlc variable by 1 year (L = 3, R = 1, C = 2)
         #left_move = ifelse(d_rlc > 0, 3, ifelse(d_rlc < 0, 2, ifelse(d_rlc == 0, 1, 0))),
         leftmove = ifelse(d_rlc > 0, 3, ifelse(d_rlc < 0, 2, 1)), # 3 = switch to left, 2 = switch to right, 1 = no change/no info
         leftmove = ifelse(is.na(leftmove), 1, leftmove), # NA = 1 = no info
         lead_leftmove = dplyr::lead(leftmove),
         leftmove = ifelse(leftmove == 1,
                           lead_leftmove,
                           leftmove),
         newgov = ifelse(yrsoffc == 1, 2, 1), # 2 = new government = 1st year in office; 1 = continuing government
         lead_newgov = dplyr::lead(newgov),
         newgov = ifelse(newgov == 1,
                         lead_newgov,
                         newgov)) %>%
  select(iso3c, year, execrlc, d_rlc, leftmove, newgov, lead_execrlc) %>%
  as.data.frame()

dpi_ideol$leftmove[is.na(dpi_ideol$leftmove)] <- 1

dpi_ideol$newgov[is.na(dpi_ideol$newgov)] <- 1

# Add DPI vars to plotting data

plot_dat <- left_join(plot_dat,
                      dpi_ideol[,c("iso3c", "year", "leftmove", "newgov", "lead_execrlc")],
                      by = c("iso3c", "year"))

plot_dat$leftmove[is.na(plot_dat$leftmove)] <- 1
plot_dat$newgov[is.na(plot_dat$newgov)] <- 1

plot_dat$leftmove_charac <- ifelse(plot_dat$leftmove == 3, "Change Towards Left",
                                   ifelse(plot_dat$leftmove == 2, "Change Towards Right", "No Change"))
plot_dat$newgov_charac <- ifelse(plot_dat$newgov == 2, "Executive Turnover", "No Turnover")

plot_dat$sig_x_move <- ifelse(plot_dat$sig == 1, plot_dat$leftmove, 0) # Left move x Significant reaction
plot_dat$sig_x_newgov <- ifelse(plot_dat$sig == 1, plot_dat$newgov, 0) # New government x Significant reaction

plot_dat$newgov_dummy <- ifelse(plot_dat$newgov == 2, 1, 0)

# Plot EMBI spread market reaction by government turnover

p <- ggplot(plot_dat, aes(y = AR, x = date)) +
  geom_jitter(aes(fill = factor(sig_x_newgov),
                  size = factor(sig_x_newgov)),
              shape = 21) +
  facet_wrap(~ newgov_charac, ncol = 1) +
  theme_minimal() +
  theme(legend.position = "none") +
  labs(x = NULL, y = NULL) +
  scale_shape_manual(values = c(21, 21, 21)) +
  scale_size_manual(values = c(1.8, 2, 2)) +
  scale_fill_manual(values = c("white", "grey20", "grey20")) +
  ggtitle(label = "Executive turnover and market reactions",
          subtitle = paste("Median abnormal change in", plot_var, "spread\nSignificant results highlighted", sep = " ")) +
  NULL
p

# Plot EMBI spread reaction by direction of ideology change

p <- ggplot(plot_dat, aes(y = AR, x = date)) +
  geom_point(aes(fill = factor(sig_x_move),
                 colour = factor(leftmove)),
             shape = 21,
             size = 2) +
  facet_wrap(~ leftmove_charac, ncol = 1) +
  theme_minimal() +
  theme(legend.position = "none") +
  labs(x = NULL, y = NULL) +
  scale_alpha_manual(values = c(0.3, 1, 1, 1)) +
  scale_colour_manual(values = c("grey20", "blue3", "red2")) +
  scale_fill_manual(values = c("white", "grey20", "blue3", "red2")) +
  ggtitle(label = "Partisan shifts and market reactions",
          subtitle = paste("Median abnormal change in", plot_var, "spread\nSignificant results highlighted", sep = " ")) +
  NULL
p

# Table with summary of EMBI spread reactions

# Select democracies only
polity <- read.csv(file.path(DATADIR, "Polity IV v2016.csv"),
                   stringsAsFactors = FALSE)

polity$iso3c <- countrycode(polity$country,
                            origin = "country.name",
                            destination = "iso3c",
                            warn = TRUE)

plot_dat<- left_join(plot_dat,
                     polity[, c("iso3c", "year", "polity2")],
                     by = c("iso3c", "year"))

plot_dat_dem <- subset(plot_dat, polity2 >= 5) # Select cases with polity = 5 or above

# Total number of elections
length(unique(plot_dat_dem$label))

# Elections with significant market reaction
sum(plot_dat_dem$sig)

# Elections with executive turnover
nrow(subset(plot_dat_dem, newgov == 2 & sig == 1))
nrow(subset(plot_dat_dem, newgov == 2))

nrow(subset(plot_dat_dem, newgov == 2 & sig == 1))/
  nrow(subset(plot_dat_dem, newgov == 2))

# Elections without executive turnover
nrow(subset(plot_dat_dem, newgov == 1 & sig == 1))
nrow(subset(plot_dat_dem, newgov == 1))

nrow(subset(plot_dat_dem, newgov == 1 & sig == 1))/
  nrow(subset(plot_dat_dem, newgov == 1))

# Significant market reactions by ideology of winner
# L = 3, R = 1, C = 2

# Elections with left winner
nrow(subset(plot_dat_dem, lead_execrlc == 3 & sig == 1))
nrow(subset(plot_dat_dem, lead_execrlc == 3))

nrow(subset(plot_dat_dem, lead_execrlc == 3 & sig == 1))/
  nrow(subset(plot_dat_dem, lead_execrlc == 3))

# Elections with right/center winner
nrow(subset(plot_dat_dem, (lead_execrlc == 1 | lead_execrlc == 2) & sig == 1))
nrow(subset(plot_dat_dem, (lead_execrlc == 1 | lead_execrlc == 2)))

nrow(subset(plot_dat_dem, (lead_execrlc == 1 | lead_execrlc == 2) & sig == 1))/
  nrow(subset(plot_dat_dem, (lead_execrlc == 1 | lead_execrlc == 2)))

# Significant market reactions by direction of partisan switch
# 3 = switch to left, 2 = switch to right, 1 = no change/no info

# Elections with any partisan switch
nrow(subset(plot_dat_dem, (leftmove == 2 | leftmove == 3) & sig == 1))
nrow(subset(plot_dat_dem, (leftmove == 2 | leftmove == 3)))

nrow(subset(plot_dat_dem, (leftmove == 2 | leftmove == 3) & sig == 1))/
  nrow(subset(plot_dat_dem, (leftmove == 2 | leftmove == 3)))

# Elections with left -> right switch
nrow(subset(plot_dat_dem, leftmove == 2 & sig == 1))
nrow(subset(plot_dat_dem, leftmove == 2))

nrow(subset(plot_dat_dem, leftmove == 2 & sig == 1))/
  nrow(subset(plot_dat_dem, leftmove == 2))

# Elections with right -> left switch
nrow(subset(plot_dat_dem, leftmove == 3 & sig == 1))
nrow(subset(plot_dat_dem, leftmove == 3))

nrow(subset(plot_dat_dem, leftmove == 3 & sig == 1))/
  nrow(subset(plot_dat_dem, leftmove == 3))

# Elections with left winner and no partisan switch
nrow(subset(plot_dat_dem, lead_execrlc == 3 & leftmove == 1 & sig == 1))
nrow(subset(plot_dat_dem, lead_execrlc == 3 & leftmove == 1))

nrow(subset(plot_dat_dem, lead_execrlc == 3 & leftmove == 1 & sig == 1))/
  nrow(subset(plot_dat_dem, lead_execrlc == 3 & leftmove == 1))


# Plots and tables for CDS event study ------------------------------------

# Merge in empirical CDS CIs 

median_AR_dat <- left_join(median_AR_cds, CI_cds, by = "country")
plot_var <- "CDS"   # Set dep. var name for plot labels/file names
plot_window <- "90"  # Set # of days of event window for plot labels

# Country codes
median_AR_dat$iso3c <- countrycode(median_AR_dat$country, origin = "country.name", destination = "iso3c")

# Election labels
median_AR_dat$label <- paste(median_AR_dat$iso3c, format(median_AR_dat$date, "%Y/%m"), sep = " ")

# Indicator of statistical significance
median_AR_dat$sig <- ifelse(median_AR_dat$AR < median_AR_dat$lb | median_AR_dat$AR > median_AR_dat$ub, 1, 0)

# Number of cases with unusual median ARs
sum(median_AR_dat$sig)
sum(median_AR_dat$sig)/nrow(median_AR_dat)

# Break down by median ARs that are lower or higher than average
sum(median_AR_dat$sig[median_AR_dat$AR < median_AR_dat$lb])/nrow(median_AR_dat)
sum(median_AR_dat$sig[median_AR_dat$AR > median_AR_dat$ub])/nrow(median_AR_dat)

# Excess spread change during election
median_AR_dat$excess_AR <- median_AR_dat$AR/median_AR_dat$median_median_AR


# Plot event study results

# Convert to long format
plot_dat <- subset(median_AR_dat,
                   select = c(country, iso3c, date, year, AR, excess_AR, lb, ub, sig, label))

plot_dat$sig_charac <- ifelse(plot_dat$sig == 1, "Market Reaction", "No Market Reaction")

# Plot median AR by change in partisanship; executive turnover

# DPI: ideology and time in office

dpi <- import(file = file.path(DATADIR, "DPI2015.dta"), format = "dta")

dpi$iso3c <- countrycode(dpi$ifs, origin = "wb", destination = "iso3c", warn = TRUE)

dpi$execrlc[dpi$execrlc == -999] <- NA
dpi$execrlc[dpi$execrlc == 0] <- NA

# Recode variables

dpi_ideol <- dpi %>%
  group_by(iso3c) %>%
  mutate(d_rlc = c(NA, diff(execrlc)), # Change in ideology
         lead_d_rlc = dplyr::lead(d_rlc), # Lead change variable by 1 year
         lead_execrlc = dplyr::lead(execrlc), # Lead rlc variable by 1 year (L = 3, R = 1, C = 2)
         #left_move = ifelse(d_rlc > 0, 3, ifelse(d_rlc < 0, 2, ifelse(d_rlc == 0, 1, 0))),
         leftmove = ifelse(d_rlc > 0, 3, ifelse(d_rlc < 0, 2, 1)), # 3 = switch to left, 2 = switch to right, 1 = no change/no info
         leftmove = ifelse(is.na(leftmove), 1, leftmove), # NA = 1 = no info
         lead_leftmove = dplyr::lead(leftmove),
         leftmove = ifelse(leftmove == 1,
                            lead_leftmove,
                            leftmove),
         newgov = ifelse(yrsoffc == 1, 2, 1), # 2 = new government = 1st year in office; 1 = continuing government
         lead_newgov = dplyr::lead(newgov),
         newgov = ifelse(newgov == 1,
                         lead_newgov,
                         newgov)) %>%
  select(iso3c, year, execrlc, d_rlc, leftmove, newgov, lead_execrlc) %>%
  as.data.frame()

dpi_ideol$leftmove[is.na(dpi_ideol$leftmove)] <- 1

dpi_ideol$newgov[is.na(dpi_ideol$newgov)] <- 1

# Add DPI vars to plotting data

plot_dat <- left_join(plot_dat,
                      dpi_ideol[,c("iso3c", "year", "leftmove", "newgov", "lead_execrlc")],
                      by = c("iso3c", "year"))

plot_dat$leftmove[is.na(plot_dat$leftmove)] <- 1
plot_dat$newgov[is.na(plot_dat$newgov)] <- 1

plot_dat$leftmove_charac <- ifelse(plot_dat$leftmove == 3, "Change Towards Left",
                                   ifelse(plot_dat$leftmove == 2, "Change Towards Right", "No Change"))
plot_dat$newgov_charac <- ifelse(plot_dat$newgov == 2, "Executive Turnover", "No Turnover")

plot_dat$sig_x_move <- ifelse(plot_dat$sig == 1, plot_dat$leftmove, 0) # Left move x Significant reaction
plot_dat$sig_x_newgov <- ifelse(plot_dat$sig == 1, plot_dat$newgov, 0) # New government x Significant reaction

plot_dat$newgov_dummy <- ifelse(plot_dat$newgov == 2, 1, 0)

# Plot CDS market reaction by government turnover

p <- ggplot(plot_dat, aes(y = AR, x = date)) +
  geom_jitter(aes(fill = factor(sig_x_newgov),
                  size = factor(sig_x_newgov)),
              shape = 21) +
  facet_wrap(~ newgov_charac, ncol = 1) +
  theme_minimal() +
  theme(legend.position = "none") +
  labs(x = NULL, y = NULL) +
  scale_shape_manual(values = c(21, 21, 21)) +
  scale_size_manual(values = c(1.8, 2, 2)) +
  scale_fill_manual(values = c("white", "grey20", "grey20")) +
  ggtitle(label = "Executive turnover and market reactions",
          subtitle = paste("Median abnormal change in", plot_var, "spread\nSignificant results highlighted", sep = " ")) +
  NULL
p

# Plot CDS market reaction by direction of ideology change

p <- ggplot(plot_dat, aes(y = AR, x = date)) +
  geom_point(aes(fill = factor(sig_x_move),
                 colour = factor(leftmove)),
             shape = 21,
             size = 2) +
  facet_wrap(~ leftmove_charac, ncol = 1) +
  theme_minimal() +
  theme(legend.position = "none") +
  labs(x = NULL, y = NULL) +
  scale_alpha_manual(values = c(0.3, 1, 1, 1)) +
  scale_colour_manual(values = c("grey20", "blue3", "red2")) +
  scale_fill_manual(values = c("white", "grey20", "blue3", "red2")) +
  ggtitle(label = "Partisan shifts and market reactions",
          subtitle = paste("Median abnormal change in", plot_var, "spread\nSignificant results highlighted", sep = " ")) +
  NULL
p

# Table with summary of CDS market reactions

# Select democracies only
polity <- read.csv(file.path(DATADIR, "Polity IV v2016.csv"),
                   stringsAsFactors = FALSE)

polity$iso3c <- countrycode(polity$country,
                            origin = "country.name",
                            destination = "iso3c",
                            warn = TRUE)

plot_dat<- left_join(plot_dat,
                     polity[, c("iso3c", "year", "polity2")],
                     by = c("iso3c", "year"))

plot_dat_dem <- subset(plot_dat, polity2 >= 5) # Select cases with polity = 5 or above

# Total number of elections
length(unique(plot_dat_dem$label))

# Elections with significant market reaction
sum(plot_dat_dem$sig)

# Elections with executive turnover
nrow(subset(plot_dat_dem, newgov == 2 & sig == 1))
nrow(subset(plot_dat_dem, newgov == 2))

nrow(subset(plot_dat_dem, newgov == 2 & sig == 1))/
  nrow(subset(plot_dat_dem, newgov == 2))

# Elections without executive turnover
nrow(subset(plot_dat_dem, newgov == 1 & sig == 1))
nrow(subset(plot_dat_dem, newgov == 1))

nrow(subset(plot_dat_dem, newgov == 1 & sig == 1))/
  nrow(subset(plot_dat_dem, newgov == 1))

# Significant market reactions by ideology of winner
# L = 3, R = 1, C = 2

# Elections with left winner
nrow(subset(plot_dat_dem, lead_execrlc == 3 & sig == 1))
nrow(subset(plot_dat_dem, lead_execrlc == 3))

nrow(subset(plot_dat_dem, lead_execrlc == 3 & sig == 1))/
nrow(subset(plot_dat_dem, lead_execrlc == 3))

# Elections with right/center winner
nrow(subset(plot_dat_dem, (lead_execrlc == 1 | lead_execrlc == 2) & sig == 1))
nrow(subset(plot_dat_dem, (lead_execrlc == 1 | lead_execrlc == 2)))

nrow(subset(plot_dat_dem, (lead_execrlc == 1 | lead_execrlc == 2) & sig == 1))/
nrow(subset(plot_dat_dem, (lead_execrlc == 1 | lead_execrlc == 2)))

# Significant market reactions by direction of partisan switch
# 3 = switch to left, 2 = switch to right, 1 = no change/no info

# Elections with any partisan switch
nrow(subset(plot_dat_dem, (leftmove == 2 | leftmove == 3) & sig == 1))
nrow(subset(plot_dat_dem, (leftmove == 2 | leftmove == 3)))

nrow(subset(plot_dat_dem, (leftmove == 2 | leftmove == 3) & sig == 1))/
  nrow(subset(plot_dat_dem, (leftmove == 2 | leftmove == 3)))

# Elections with left -> right switch
nrow(subset(plot_dat_dem, leftmove == 2 & sig == 1))
nrow(subset(plot_dat_dem, leftmove == 2))

nrow(subset(plot_dat_dem, leftmove == 2 & sig == 1))/
  nrow(subset(plot_dat_dem, leftmove == 2))

# Elections with right -> left switch
nrow(subset(plot_dat_dem, leftmove == 3 & sig == 1))
nrow(subset(plot_dat_dem, leftmove == 3))

nrow(subset(plot_dat_dem, leftmove == 3 & sig == 1))/
  nrow(subset(plot_dat_dem, leftmove == 3))

# Elections with left winner and no partisan switch
nrow(subset(plot_dat_dem, lead_execrlc == 3 & leftmove == 1 & sig == 1))
nrow(subset(plot_dat_dem, lead_execrlc == 3 & leftmove == 1))

nrow(subset(plot_dat_dem, lead_execrlc == 3 & leftmove == 1 & sig == 1))/
  nrow(subset(plot_dat_dem, lead_execrlc == 3 & leftmove == 1))

